const path = require('path');
const fs = require('fs');
let lvResInProjPath = path.join(__dirname, "../../assets/GameAb/lv/")
let lvIconProjPath = path.join(__dirname, "../iconGenerator/icons/")
let resNameInProjArray = []
let iconsInToolPackArray = []
traverseDirectorySync(lvResInProjPath, ".json", resNameInProjArray)
traverseDirectorySync(lvIconProjPath, ".jpg", iconsInToolPackArray)

function traverseDirectorySync(dirPath, fileExt, outArray) {
    console.log(`目录: ${dirPath}，扩展:${fileExt}`);
    const files = fs.readdirSync(dirPath); // 读取目录中的所有文件和文件夹

    files.forEach(file => {
        const fullPath = path.join(dirPath, file);
        const stats = fs.statSync(fullPath); // 获取文件或文件夹的状态信息

        if (stats.isDirectory()) {
            console.log(`目录: ${fullPath}`);
            // 如果是目录，递归调用
            traverseDirectorySync(fullPath, fileExt, outArray);
        } else {
            if (path.extname(fullPath) == fileExt) {
                const fileNameWithoutExt = path.basename(fullPath, path.extname(fullPath));
                outArray.push(fileNameWithoutExt)
            }
        }
    });
}

let toBeDeleteds = []
console.log(`打包的个数:${iconsInToolPackArray.length},项目中的个数:${resNameInProjArray.length}，差值:${resNameInProjArray.length - iconsInToolPackArray.length}`)
resNameInProjArray.forEach((name) => {
    if (iconsInToolPackArray.indexOf(name) == -1) {
        console.log(`${name}项目中有，打包没有`)
        toBeDeleteds.push(name)
    }
})

iconsInToolPackArray.forEach((name) => {
    if (resNameInProjArray.indexOf(name) == -1) {
        console.log(`${name}打包有，项目中没有`)
        toBeDeleteds.push(name)
    }
})

console.log("toBeDeleteds:", toBeDeleteds.toString())

deleteFilesByPrefix(lvResInProjPath, toBeDeleteds)
function deleteFilesByPrefix(dirPath, prefixes) {
    const files = fs.readdirSync(dirPath); // 读取目录中的所有文件
    files.forEach(file => {
        const fullPath = path.join(dirPath, file);
        const stats = fs.statSync(fullPath); // 获取文件状态信息
        if (stats.isFile()) {
            // 检查文件前缀是否在数组中
            let fileName = path.basename(fullPath)
            // console.log("处理文件：", fullPath, fileName)
            for (let i = 0; i < prefixes.length; i++) {
                let prefix = prefixes[i]
                if (fileName.startsWith(prefix)) {
                    console.log(`准备删除: ${fullPath}`);
                    try {
                        // fs.unlinkSync(fullPath); // 删除文件
                        console.log(`已删除: ${fullPath}`);
                    } catch (err) {
                        console.error(`删除失败: ${fullPath}`, err);
                    }
                }
            }
        }
    });
}